package com.hcinfos.gsoo.ui;

import java.io.File;
import java.io.IOException;

import javax.mail.MessagingException;
import javax.mail.internet.AddressException;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.WindowManager;
import android.webkit.CookieManager;
import android.webkit.CookieSyncManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ToggleButton;

import com.hcinfos.gsoo.R;
import com.hcinfos.gsoo.config.Common;
import com.hcinfos.gsoo.config.Constants;
import com.hcinfos.gsoo.config.Urls;
import com.hcinfos.gsoo.enity.Version;
import com.hcinfos.gsoo.https.HttpClientUtil;
import com.hcinfos.gsoo.interaze.DialogCallBack;
import com.hcinfos.gsoo.json.VersionJson;
import com.hcinfos.gsoo.util.ApkDownloadUtil;
import com.hcinfos.gsoo.util.DialogUtil;
import com.hcinfos.gsoo.util.EmailSender;
import com.hcinfos.gsoo.util.ImageUtil;
import com.hcinfos.gsoo.util.LogUtil;
import com.hcinfos.gsoo.util.SharePreferenceUtil;
import com.hcinfos.gsoo.util.VersionUtil;
import com.weibo.sdk.android.Oauth2AccessToken;
import com.weibo.sdk.android.Weibo;
import com.weibo.sdk.android.WeiboAuthListener;
import com.weibo.sdk.android.WeiboDialogError;
import com.weibo.sdk.android.WeiboException;
import com.weibo.sdk.android.api.UsersAPI;
import com.weibo.sdk.android.net.RequestListener;

public class SettingActivity extends Activity implements OnClickListener {
	private TextView reg_tv;
	private ImageButton left_ib;
	private TextView center_tv;
	private ToggleButton sina_tb;
	private ToggleButton mode_tb;
	private RelativeLayout clearCache_rl;
	private RelativeLayout version_rl;
	private RelativeLayout advise_rl;
	private TextView version_num_tv;
	private RelativeLayout sina_rl;

	private EditText advise_et;
	private EditText advise_contact;
	private RelativeLayout advise_dialog_rl;
	private Dialog advise_dialog;
	private Button confirm_dialog_ok_btn;
	private Button confirm_dialog_cancel_btn;
	private TextView tip_title;
	private TextView report_tv_one;
	private TextView name_tv;

	private static final String CONSUMER_KEY = "2912786215";// 替换为开发者的appkey，例如"1646212860";2912786215
	private static final String REDIRECT_URL = "http://www.sina.com";
	private Weibo mWeibo;
	private SharePreferenceUtil util;

	private final int GET_WEIBO_NAME = 0x1120;
	private final int NEW_VERSION = GET_WEIBO_NAME + 1;
	private final int GET_VERSION_FAIL = GET_WEIBO_NAME + 2;
	private final int NO_NEW_VERSION = GET_WEIBO_NAME + 3;

	private TextView cache_tv;
	private Dialog versionDialog;
	private RelativeLayout mode_rl;
	private RelativeLayout intro_rl;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		int width = this.getWindowManager().getDefaultDisplay().getWidth();
		Common.PROPORTION = width / 320f;
		Common.WIDTH = width;
		setContentView(R.layout.activity_setting);
		util = new SharePreferenceUtil(this, "setting");
		versionDialog = DialogUtil.createProgressDialog(this, "检查更新",
				"正在检查中,请稍等!");
		initRes();
	}

	private void initRes() {
		sina_rl = (RelativeLayout) findViewById(R.id.sina_rl);
		sina_rl.setOnClickListener(this);
		left_ib = (ImageButton) findViewById(R.id.left_ib);
		left_ib.setOnClickListener(this);
		reg_tv = (TextView) findViewById(R.id.reg_tv);
		reg_tv.setVisibility(View.GONE);
		center_tv = (TextView) findViewById(R.id.center_tv);
		center_tv.setText("设置");

		sina_tb = (ToggleButton) findViewById(R.id.sina_tb);
		sina_tb.setClickable(false);
		mode_tb = (ToggleButton) findViewById(R.id.mode_tb);
		clearCache_rl = (RelativeLayout) findViewById(R.id.clearCache_rl);
		clearCache_rl.setOnClickListener(this);
		version_rl = (RelativeLayout) findViewById(R.id.version_rl);
		version_rl.setOnClickListener(this);
		advise_rl = (RelativeLayout) findViewById(R.id.advise_rl);
		advise_rl.setOnClickListener(this);

		version_num_tv = (TextView) findViewById(R.id.version_num_tv);
		try {
			version_num_tv.setText(VersionUtil.getVersionName(this));
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		LayoutInflater inflater = getLayoutInflater();
		advise_dialog_rl = (RelativeLayout) inflater.inflate(
				R.layout.report_dialog_view, null);
		advise_et = (EditText) advise_dialog_rl.findViewById(R.id.report_et);
		advise_contact = (EditText) advise_dialog_rl
				.findViewById(R.id.contact_et);
		confirm_dialog_cancel_btn = (Button) advise_dialog_rl
				.findViewById(R.id.confirm_dialog_cancel_btn);
		confirm_dialog_cancel_btn.setOnClickListener(this);
		confirm_dialog_ok_btn = (Button) advise_dialog_rl
				.findViewById(R.id.confirm_dialog_ok_btn);
		confirm_dialog_ok_btn.setText("提交");
		confirm_dialog_ok_btn.setOnClickListener(this);
		tip_title = (TextView) advise_dialog_rl.findViewById(R.id.tip_title);
		tip_title.setText("建议反馈");
		report_tv_one = (TextView) advise_dialog_rl
				.findViewById(R.id.report_tv_one);
		report_tv_one.setText("你的建议");
		name_tv = (TextView) findViewById(R.id.name_tv);

		mWeibo = Weibo.getInstance(CONSUMER_KEY, REDIRECT_URL);
		cache_tv = (TextView) findViewById(R.id.cache_tv);
		mode_rl = (RelativeLayout) findViewById(R.id.mode_rl);
		mode_rl.setOnClickListener(this);

		intro_rl = (RelativeLayout) findViewById(R.id.intro_rl);
		intro_rl.setOnClickListener(this);
	}

	private long size;

	@Override
	protected void onResume() {
		super.onResume();
		String name = util.loadStringSharedPreference("weibo_name");
		name_tv.setText(name);
		if (util.loadStringSharedPreference("token") != null) {
			sina_tb.setChecked(true);
		} else {
			sina_tb.setChecked(false);
		}
		try {
			size = ImageUtil.getFileSize(new File(Constants.DIR));
			String sizeStr = ImageUtil.FormetFileSize(size);
			cache_tv.setText(sizeStr);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.left_ib:
			finish();
			break;
		case R.id.clearCache_rl:
			if (size == 0) {
				Toast.makeText(this, "暂无缓存数据", 500).show();
				return;
			}
			DialogUtil.createCallLoginDialog(this, "你是否确定清空缓存",
					new DialogCallBack() {

						@Override
						public void viewClick() {

						}

						@Override
						public void ok() {
							clearThread();
						}

						@Override
						public void init(Object obj) {

						}

						@Override
						public void cancel() {

						}
					}, "清空", "取消");
			break;
		case R.id.version_rl:
			if (!isDownloading) {
				if (versionDialog != null)
					versionDialog.show();
				checkVersion();
			} else {
				Toast.makeText(SettingActivity.this, "正在下载中，请稍等!", 500).show();
			}
			break;
		case R.id.advise_rl:
			if (advise_dialog == null) {
				advise_dialog = new Dialog(this, R.style.QuitDialog);
				advise_dialog.setContentView(advise_dialog_rl);
				Window dialogWindow = advise_dialog.getWindow();
				WindowManager.LayoutParams lp = dialogWindow.getAttributes();
				dialogWindow.setGravity(Gravity.CENTER);
				lp.width = (int) (250 * Common.PROPORTION); // 宽度
				lp.height = (int) (300 * Common.PROPORTION); // 高度
				dialogWindow.setAttributes(lp);

			}
			advise_dialog.show();
			break;
		case R.id.confirm_dialog_cancel_btn:
			if (advise_dialog != null)
				advise_dialog.dismiss();
			break;
		case R.id.confirm_dialog_ok_btn:
			String advise = advise_et.getText().toString();
			String contact = advise_contact.getText().toString();
			if (advise.length() == 0) {
				advise_et.setHintTextColor(Color.RED);
				advise_et.setHint("请输入你的建议");
			} else {
				if (advise_dialog != null)
					advise_dialog.dismiss();
				String str = null;
				if (contact.length() != 0) {
					str = "建议内容:" + advise + " 联系方式:" + contact;
				} else {
					str = "建议内容:" + advise;
				}
				sendMail(str);
				Toast.makeText(getBaseContext(), "谢谢你的建议!", Toast.LENGTH_LONG)
						.show();
			}

			break;
		case R.id.sina_rl:
			if (sina_tb.isChecked()) {
				clear();
			} else {
				mWeibo.authorize(SettingActivity.this, new AuthDialogListener());
			}
			break;
		case R.id.mode_rl:
			if (mode_tb.isChecked()) {
				util.saveSharedPreferences("loadMode", false);
				mode_tb.setChecked(false);
			} else {
				util.saveSharedPreferences("loadMode", true);
				mode_tb.setChecked(true);
			}
			break;
		case R.id.intro_rl:
			// Intent intent = new Intent(SettingActivity.this,
			// IntroFriendActivity.class);
			// startActivity(intent);

			Intent mIntent = new Intent(Intent.ACTION_VIEW);
			mIntent.putExtra(
					"sms_body",
					"#Gsoo客户端#可以查看周围海量信息,又方便又有优惠哦，"
							+ "并且不知道附近的有哪些商家信息可以使用搜信在线求助!,既好玩，"
							+ "又实惠推荐给大家试试http://www.gsoo.com/apps/android/v1.1/gsoo.apk");
			mIntent.setType("vnd.android-dir/mms-sms");
			startActivity(mIntent);
			break;
		}
	}

	private void clearThread() {

		new Thread(new Runnable() {

			@Override
			public void run() {

				ImageUtil.clear(new File(Constants.DIR));
				SettingActivity.this.runOnUiThread(new Runnable() {

					@Override
					public void run() {
						cache_tv.setText("");
						size = 0;
					}
				});
			}
		}).start();
	}

	private void clear() {
		sina_tb.setChecked(false);
		name_tv.setText("");
		util.removeKey("token");
		util.removeKey("expires_in");
		util.removeKey("weibo_name");
		CookieSyncManager.createInstance(getApplicationContext());
		CookieSyncManager.getInstance().startSync();
		CookieManager.getInstance().removeAllCookie();
	}

	class AuthDialogListener implements WeiboAuthListener {

		@Override
		public void onComplete(Bundle values) {

			String token = values.getString("access_token");
			String expires_in = values.getString("expires_in");
			String uid = values.getString("uid");
			LogUtil.d("wxf", "uId:" + uid);
			util.saveSharedPreferences("token", token);
			util.saveSharedPreferences("expires_in", expires_in);
			sina_tb.setChecked(true);
			if (uid == null)
				return;
			getWeiboName(token, expires_in, uid);

		}

		@Override
		public void onWeiboException(WeiboException e) {
			sina_tb.setChecked(false);
		}

		@Override
		public void onError(WeiboDialogError e) {
			sina_tb.setChecked(false);
		}

		@Override
		public void onCancel() {
			sina_tb.setChecked(false);
		}
	}

	private void getWeiboName(String token, String expires_in, String uid) {
		Oauth2AccessToken access_token = new Oauth2AccessToken(token,
				expires_in);
		UsersAPI usersAPI = new UsersAPI(access_token);

		usersAPI.show(Long.parseLong(uid), new RequestListener() {

			@Override
			public void onIOException(IOException arg0) {

				LogUtil.d("wxf", "IOException:" + arg0.toString());
			}

			@Override
			public void onError(WeiboException arg0) {
				LogUtil.d("wxf", "IOException:" + arg0.toString());
			}

			@Override
			public void onComplete(String result) {

				LogUtil.d("wxf", "result:" + result);
				try {
					JSONObject obj = new JSONObject(result);
					String name = (String) obj.get("screen_name");
					util.saveSharedPreferences("weibo_name", name);
					Message msg = handler.obtainMessage();
					msg.what = GET_WEIBO_NAME;
					msg.obj = name;
					handler.sendMessage(msg);
					Log.i("wxf", "name:" + name);
				} catch (JSONException e) {
					e.printStackTrace();
				}

			}
		});
	}

	private Version version;

	private void checkVersion() {
		new Thread(new Runnable() {

			@Override
			public void run() {

				try {
					String result = HttpClientUtil.getFromWebByHttpClient(
							SettingActivity.this,
							"http://www.gsoo.com/apps/version.jsp");
					if (result != null) {
						version = VersionJson.getVersionByJson(result);
						if (VersionJson.state == 200) {
							if (version == null)
								return;
							int currentCode = VersionUtil
									.getCurrentLocalVersion(SettingActivity.this);
							if (version.getVersionCode() > currentCode) {
								Message msg = handler.obtainMessage();
								msg.what = NEW_VERSION;
								handler.sendMessage(msg);
							} else {
								Message msg = handler.obtainMessage();
								msg.what = NO_NEW_VERSION;
								handler.sendMessage(msg);
							}

						}
					} else {
						Message msg = handler.obtainMessage();
						msg.what = GET_VERSION_FAIL;
						handler.sendMessage(msg);
					}
				} catch (Exception e) {
					Message msg = handler.obtainMessage();
					msg.what = GET_VERSION_FAIL;
					handler.sendMessage(msg);
				}
			}
		}).start();
	}

	private boolean isDownloading = false;
	Handler handler = new Handler() {
		public void handleMessage(android.os.Message msg) {
			if (versionDialog != null)
				versionDialog.dismiss();
			switch (msg.what) {
			case GET_WEIBO_NAME:
				if (msg.obj != null) {
					name_tv.setText(msg.obj.toString());
				}
				break;
			case GET_VERSION_FAIL:
				Toast.makeText(SettingActivity.this, "获取失败", 500).show();
				break;
			case NEW_VERSION:
				LogUtil.d("wxf", "NEW_VERSION");
				DialogUtil.versionDialog(SettingActivity.this,
						version.getVersionDes(), new DialogCallBack() {

							@Override
							public void viewClick() {

							}

							@Override
							public void ok() {
								try {
									isDownloading = true;
									ApkDownloadUtil util = new ApkDownloadUtil(
											getApplicationContext(),
											handler,
											Urls.COMMON_URL
													+ version.getApkUrl(),
											String.valueOf(getText(R.string.app_name)
													+ "_"
													+ VersionUtil
															.getVersionName(SettingActivity.this)));
									util.start();

								} catch (Exception e) {
								}
							}

							@Override
							public void init(Object obj) {

							}

							@Override
							public void cancel() {

							}
						}, "升级", "取消");

				break;
			case NO_NEW_VERSION:
				Toast.makeText(SettingActivity.this, "已经是最新版本", 500).show();
				break;
			case ApkDownloadUtil.MSG_DOWNING:
				Toast.makeText(getApplicationContext(), R.string.downloadStart,
						Toast.LENGTH_LONG).show();
				break;
			case ApkDownloadUtil.MSG_FINISH:
				isDownloading = false;
				String path = (String) msg.obj;
				installAPK(path);
				break;
			case ApkDownloadUtil.MSG_FAILURE:
				isDownloading = false;
				Toast.makeText(getApplicationContext(),
						R.string.downloadFailure, Toast.LENGTH_LONG).show();
				break;

			}

		};
	};

	private void installAPK(String path) {

		Uri uri = Uri.fromFile(new File(path));
		Intent intent = new Intent(Intent.ACTION_VIEW);
		intent.setDataAndType(uri, "application/vnd.android.package-archive");
		startActivity(intent);
	}

	private void sendMail(final String content) {

		new Thread(new Runnable() {

			@Override
			public void run() {
				try {
					EmailSender sender = new EmailSender();
					// 设置服务器地址和端口，网上搜的到
					sender.setProperties("smtp.163.com", "25");
					// 分别设置发件人，邮件标题和文本内容
					sender.setMessage("wangxinfeng_1990@163.com", "反馈建议",
							content);
					// 设置收件人
					sender.setReceiver(new String[] { "gsoo@gsoo.com" });
					// 添加附件，我这里注释掉，因为有人跟我说这行报错...
					// 这个附件的路径是我手机里的啊，要发你得换成你手机里正确的路径
					// sender.addAttachment("/default.prop");
					// 发送邮件
					sender.sendEmail("smtp.163.com",
							"wangxinfeng_1990@163.com", "feng123456789");
				} catch (AddressException e) {
					Log.e("wxf", "AddressException:" + e.toString());
					e.printStackTrace();
				} catch (MessagingException e) {
					Log.e("wxf", "MessagingException:" + e.toString());
					e.printStackTrace();
				}
			}
		}).start();
		// 发送方的邮箱名及密码。
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {

		if (keyCode == KeyEvent.KEYCODE_BACK) {

			finish();
		}
		return super.onKeyDown(keyCode, event);
	}
}
